package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.KpiPaintReportVO.OperationalVO;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.KpiResponseForOut;
import com.ugoodtech.mdcc.web.dto.PaintResponse;
import com.ugoodtech.mdcc.web.service.ExportReportService;
import com.ugoodtech.mdcc.web.service.GetLeanPaintKpiReportService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/getLeanPaintKpi")
public class GetLeanPaintKpiReportController extends BaseController {

    private static final Logger Logger = LoggerFactory.getLogger(GetLeanPaintKpiReportController.class);

    @Autowired
    private GetLeanPaintKpiReportService getLeanPaintKpiReportService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ExportReportService exportReportService;
    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @ApiOperation("获取kpi表格数据")
    @RequestMapping(value = "getLeanPaintKpiReport", method = RequestMethod.GET)
    public JsonResponse getLeanPaintKpiReport(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long userId,
                                              @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                              @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId) {
        isUserLogin();
        User user = userRepository.findOne(userId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        ModuleAuthority moduleAuthority = moduleAuthorityRepository.findByName(Constants.PAINT_REPORT_CHECK);
        boolean tf = user.getAuthorities().contains(moduleAuthority);
        if (tf == false) {
            return JsonResponse.errorResponseWithError("抱歉", "没有权限查看精益板喷KPI报表");
        }
        return getLeanPaintKpiReportService.getLeanPaintKpiReport(reportId, stationId, null);
    }

    @ApiOperation("导出kpi表格数据")
    @RequestMapping(value = "getKpiResponseOut", method = RequestMethod.POST)
    public JsonResponse getKpiResponseOut(Long loginUserId, HttpServletRequest request, HttpServletResponse response,
                                          @RequestBody KpiResponseForOut kpiResponse,
                                          @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                          @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId) throws Exception {
        isUserLogin();
        OperationalVO operationalVO = (OperationalVO) getLeanPaintKpiReport(loginUserId, reportId, stationId).getData();
        operationalVO.setResponseKpi(kpiResponse.getKpiResponse());
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        System.out.println(request.getSession().getServletContext().getRealPath(""));

        String templetPath = request.getSession().getServletContext().getRealPath("");

        String filePath = exportReportService.genKpiReport(operationalVO, templetPath);
        Station station = stationRepository.findOne(stationId);
        userLogService.addUserLog(user, station.getStationNum(),
                LogConstants.operate_type_send_export,
                LogConstants.business_type_lean_paint_report_statistics, null, null);
        filePath = Constants.v_starServiceUrl + filePath;
//        filePath = "http://vr.duluxdesigner.com.cn" + filePath;
//        filePath = "http://116.62.64.140:51002" + filePath;
        return JsonResponse.successResponseWithData(filePath);
    }


    @ApiOperation("获取kpi列表分页--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getPaintKpiList", method = RequestMethod.GET)
    public JsonResponse getPaintKpiList(Pageable pageable,
                                        @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                        @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                        @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                        @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                        @ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                        @ApiParam("维修站ID") @RequestParam(value = "stationId", required = false) Long stationId,
                                        @ApiParam("用户ID") @RequestParam(value = "userId", required = false) Long userId,
                                        @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        ModuleAuthority moduleAuthority = moduleAuthorityRepository.findByName(Constants.PAINT_REPORT_CHECK);
        boolean tf = user.getAuthorities().contains(moduleAuthority);
        if (tf == false) {
            return JsonResponse.errorResponseWithError("抱歉", "没有权限查看精益板喷KPI报表");
        }
        return getLeanPaintKpiReportService.getPaintKpiList(user, pageable, stationId, province, city, category, brand, userId,departmentId);
    }


    @ApiOperation("查出这家维修站所有的精益版喷报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "report_paints", method = RequestMethod.GET)
    public JsonResponse getStationPaintReports(Pageable pageable, @RequestParam(name = "stationId") Long stationId) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        builder.and(qStationReport.station.id.eq(stationId));
        Page<StationReport> stationReportList = stationReportRepository.findAll(builder, pageable);
        List<PaintResponse> paintResponseList = new ArrayList<>();
        for (StationReport report : stationReportList) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            PaintResponse paintResponse = new PaintResponse(report, true, userProfile.getRealName());
            User editUser = report.getEditUser();
            if (editUser != null) {
                userProfile = userProfileRepository.findByUserId(editUser.getId());
                paintResponse.setEditUserName(userProfile.getRealName());
            }
            paintResponseList.add(paintResponse);
        }
        Page<PaintResponse> paintResponsePage = new PageImpl(paintResponseList, pageable, stationReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(paintResponsePage);
    }


    @ApiOperation("获取筛选出的维修站--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getMyStation", method = RequestMethod.GET)
    public JsonResponse getMyStation(Pageable pageable,
                                     @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                     @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                     @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                     @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                     @ApiParam("维修站名字") @RequestParam(value = "stationName", required = false) String stationName) {
        isUserLogin();
        return getLeanPaintKpiReportService.getMyStation(new User(), province, city, brand, category, stationName, pageable);
    }

}
